<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>画直线</title>
    <style>
        canvas {
            margin: 0 auto;
            border: 1px black solid;
            display: block;
        }
    </style>
</head>
<body>
    <canvas width="500px" height="500px" id="can"></canvas>

    <script>
        let can = document.querySelector("#can");
        let ctx = can.getContext('2d');

        drawLine(100, 100, 100, 400, "yellow", 5);
        drawLine(100, 400, 400, 400, "blue", 5);
        drawLine(400, 400, 400, 100, "purple", 5);
        drawLine(400, 100, 100, 100, "red", 5);


        /**
         *
         * @param x1   起点 x 坐标
         * @param y1   起点 y 坐标
         * @param x2   终点 x 坐标
         * @param y2   终点 y 坐标
         * @param color 线条颜色
         * @param width 线宽
         */
        function drawLine (x1, y1, x2, y2, color, width) {
            ctx.beginPath();
            ctx.lineWidth = width;
            ctx.moveTo(x1, y1);
            ctx.lineTo(x2, y2);
            ctx.strokeStyle = color;
            ctx.stroke();
            ctx.closePath();
        }
    </script>

</body>
</html>
